package com.javaDemo.clone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class CloneUtils {
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T obj) {
        T cloneObj = null;
        try {
            //读取对象字节数据
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            oos.close();
            //分配内存空间，写入原始对象，生成新对象
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            //返回新的对象，并做类型转换
            cloneObj = (T) ois.readObject();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cloneObj;


    }
    // public static void main(String[] args) {
    //     Config config = new Config();
    //     config.useClusterServers()
    //             .addNodeAddress("redis://10.23.3.24:7000")
    //             .addNodeAddress("redis://10.23.3.24:7001")
    //             .addNodeAddress("redis://10.23.3.24:7002")
    //     RedissonClient redisson = Redisson.create(config);
    //     RBlockingQueue<String> blockingQueue = redisson.getBlockingQueue("dest_queue2");
    //     RDelayedQueue<String> delayedQueue = redisson.getDelayedQueue(blockingQueue);
    //     new Thread() {
    //         public void run() {
    //             while(true) {
    //                 try {
    //                     //阻塞队列有数据就返回，否则wait
    //                     String take = blockingQueue.take();
    //                     System.out.println("take:"+take);
    //                     long time = Long.valueOf(take.split("---")[0]);
    //                     //消费可能产生的延迟
    //                     System.out.println("delay:"+(System.currentTimeMillis()-time-2*60*1000));
    //                 } catch (InterruptedException e) {
    //                     e.printStackTrace();
    //                 }
    //             }
    //         };
    //     }.start();
    //
    //     for(int i=1;i<=100000;i++) {
    //         // 向阻塞队列放入数据
    //         long time = System.currentTimeMillis();
    //         delayedQueue.offer(time+"---"+i, 2, TimeUnit.MINUTES);
    //     }
    //     delayedQueue.destroy();
    // }
}